Public Partial Class FrmFacturaVentaABM
    Inherits System.Web.UI.Page
    Public Cliente As CapaDeNegocios.nCliente = New CapaDeNegocios.nCliente
    Public Factura As CapaDeNegocios.nFactura = New CapaDeNegocios.nFactura
    Public Talonario As CapaDeNegocios.nTalonario = New CapaDeNegocios.nTalonario
    Public TipoTalonario As CapaDeNegocios.nTipoTalonario = New CapaDeNegocios.nTipoTalonario
    Public Concepto As CapaDeNegocios.nConcepto = New CapaDeNegocios.nConcepto
    Public CategoriaFiscal As CapaDeNegocios.nCategoriaFiscal = New CapaDeNegocios.nCategoriaFiscal
    Public Remito As CapaDeNegocios.nRemitoServicios = New CapaDeNegocios.nRemitoServicios()
    Public DetalleFacturaVenta As CapaDeNegocios.nDetalleFacturaVenta = New CapaDeNegocios.nDetalleFacturaVenta()

    Dim DtsConcepto As DataSet
    Dim DtsRemito As DataSet
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Login") = "Anonimo" Then
            Response.Redirect("/")
        End If

        If Not Page.IsPostBack Then
            LimpiarCampos()
            LlenarCboCliente()
            LLenarCboConceptos()
            DtsRemito = New DataSet()
            DtsRemito.Tables.Add("TblRemito")
            DtsRemito.Tables(0).Columns.Add("Numero")
            DtsRemito.Tables(0).Columns.Add("CodigoRemito")
            DtsRemito.Tables(0).Columns.Add("Fecha")
            DtsRemito.Tables(0).Columns.Add("SubTotal")
            DtsRemito.Tables(0).Columns.Add("Iva")
            DtsRemito.Tables(0).Columns.Add("Valor")
            Session("DtsVentasRemito") = DtsRemito

            DtsConcepto = New DataSet()
            DtsConcepto.Tables.Add("TblConcepto")
            DtsConcepto.Tables(0).Columns.Add("DescripcionConcepto")
            DtsConcepto.Tables(0).Columns.Add("CodigoConcepto")
            DtsConcepto.Tables(0).Columns.Add("SubTotal")
            DtsConcepto.Tables(0).Columns.Add("Iva")
            DtsConcepto.Tables(0).Columns.Add("Total")
            Session("DtsVentas") = DtsConcepto
            LnkListadoFacturas.OnClientClick = "javascript:var popup = window.open('FrmListadoFacturaVenta.aspx',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=YES,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
        End If
    End Sub
    Sub LimpiarCampos()
        '        TxtNumero.Text = "00000000"
        '        TxtNumero.Enabled = False}
        LblFecha.Text = Now.Date.ToShortDateString()
        TxtTotal.Text = "0,00"
    End Sub
    Sub LlenarCboCliente()
        CboClientes.Items.Clear()
        CboClientes.Items.Add(New ListItem("Seleccione...", -1))

        CboClientes.DataSource = Cliente.Listar("", "", "", "", "", "", "", "", "", "", "", "")
        CboClientes.DataTextField = "RazonSocial"
        CboClientes.DataValueField = "CodigoCliente"
        CboClientes.DataBind()
        If CboClientes.Items.Count > 1 Then
            CboClientes.SelectedIndex = 0
            If Cliente.Listar(CboClientes.SelectedValue.ToString(), "", "", "", "", "", "", "", "", "", "", "").Tables(0).Rows(0)("CodigoCategoria").ToString() = "1" Then
                LblNumero.Text = "A-0001-"
                TxtNumero.Text = Replace(Factura.ObtenerNumero("1").ToString().PadLeft(8), " ", "0")
            Else
                LblNumero.Text = "B-0001-"
                TxtNumero.Text = Replace(Factura.ObtenerNumero("2").ToString().PadLeft(8), " ", "0")
            End If
            'TxtNumero.Text = "00123333"
            VerificarTalonario()
            LLenarCboRemitos()
        End If
    End Sub
    Sub LLenarCboConceptos()
        CboConceptos.Items.Clear()
        CboConceptos.Items.Add(New ListItem("Seleccione...", -1))
        CboConceptos.DataSource = Concepto.ListarConcepto(0, "", "", 0, "VENTA")
        CboConceptos.DataTextField = "Descripcion"
        CboConceptos.DataValueField = "CodigoConcepto"
        CboConceptos.DataBind()
        LnkAgregarConcepto.Enabled = CboConceptos.Items.Count > 1
        If CboConceptos.Items.Count > 1 Then
            CboConceptos.SelectedIndex = 0


        End If
    End Sub

    Sub LLenarCboRemitos()
        CboRemitos.Items.Clear()
        CboRemitos.Items.Add(New ListItem("Seleccione...", -1))
        If CboClientes.Items.Count > 1 Then
            CboRemitos.DataSource = Remito.BuscarFiltrado("", "", "", "", "", "", CboClientes.SelectedValue.ToString(), "-1", "ACTIVO")
            CboRemitos.DataTextField = "Numero"
            CboRemitos.DataValueField = "CodigoRemito"
            CboRemitos.DataBind()
            CboRemitos.Enabled = CboRemitos.Items.Count > 1
            LnkAgregarRemito.Visible = CboRemitos.Enabled
            LnkMasInfo.Visible = CboRemitos.Enabled
            If CboRemitos.Items.Count > 1 Then
                CboRemitos.SelectedIndex = 0
            End If
        End If

    End Sub

    Protected Sub LnkAgregarConcepto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkAgregarConcepto.Click
        If (CboConceptos.SelectedValue <> -1) Then

            CboConceptos.SelectedItem.Enabled = False
            Dim dr As DataRow
            Dim IVA As Double = (Concepto.DarIva(CboConceptos.SelectedValue) / 100)
            DtsConcepto = Session("DtsVentas")
            dr = DtsConcepto.Tables(0).NewRow()
            dr("DescripcionConcepto") = CboConceptos.Items(CboConceptos.SelectedIndex).Text.ToString()
            dr("CodigoConcepto") = CboConceptos.SelectedValue.ToString()
            dr("Total") = (Math.Round(CDbl(TxtTotal.Text), 2)).ToString()
            dr("IVA") = (Math.Round(CDbl(TxtTotal.Text) * IVA, 2)).ToString()
            '            dr("SubTotal") = (Math.Round(CDbl(TxtTotal.Text) / IVA, 2)).ToString()
            dr("SubTotal") = (Math.Round(CDbl(TxtTotal.Text) - (CDbl(TxtTotal.Text) * IVA), 2)).ToString()

            DtsConcepto.Tables(0).Rows.Add(dr)
            LblTotal.Text = (CDbl(LblTotal.Text) + CDbl(dr("Total").ToString())).ToString()
            LblSubtotal.Text = (CDbl(LblSubtotal.Text) + CDbl(dr("SubTotal").ToString())).ToString()
            LblIva.Text = (CDbl(LblIva.Text) + CDbl(dr("IVA").ToString())).ToString()
            GridConcepto.DataSource = DtsConcepto
            GridConcepto.DataBind()
            TxtTotal.Text = "0,00"
            CboConceptos.Enabled = False
            Dim i As Integer
            For i = 0 To CboConceptos.Items.Count() - 1
                CboConceptos.Enabled = CboConceptos.Enabled Or CboConceptos.Items(i).Enabled
            Next
            TxtTotal.Enabled = CboConceptos.Enabled
            CboClientes.Enabled = False
        End If

    End Sub
    Protected Sub GridConcepto_RowCommand(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridConcepto.RowCommand
        If e.CommandName = "Remover" Then
            CboConceptos.Items(CboConceptos.Items.IndexOf(CboConceptos.Items.FindByValue(CInt(e.CommandSource.Parent.Parent.FindControl("HFIdConcepto").value.ToString())))).Enabled = True
            LblTotal.Text = (CDbl(LblTotal.Text) - CDbl(e.CommandSource.Parent.Parent.FindControl("LblTotal").text.ToString())).ToString()
            LblSubtotal.Text = (CDbl(LblSubtotal.Text) - CDbl(e.CommandSource.Parent.Parent.FindControl("LblSubtotal").text.ToString())).ToString()
            LblIva.Text = (CDbl(LblIva.Text) - CDbl(e.CommandSource.Parent.Parent.FindControl("LblIva").text.ToString())).ToString()
            DtsConcepto = Session("DtsVentas")
            DtsConcepto.Tables(0).Rows.Remove(DtsConcepto.Tables(0).Rows(CInt(e.CommandSource.parent.parent.RowIndex)))
            GridConcepto.DataSource = DtsConcepto
            GridConcepto.DataBind()
            CboConceptos.Enabled = Not CboConceptos.Text = ""
            If TxtTotal.Text = "0" Then
                TxtTotal.Text = "0,00"
            End If
            CboClientes.Enabled = DtsConcepto.Tables(0).Rows.Count = 0
        End If
    End Sub
    Protected Sub LnkAgregarRemito_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkAgregarRemito.Click
        If CboRemitos.SelectedValue <> -1 Then

            CboClientes.Enabled = False
            Dim dr As DataRow
            Dim IVA As Double = 0.21
            DtsRemito = Session("DtsVentasRemito")
            dr = DtsRemito.Tables(0).NewRow()
            dr("Numero") = CboRemitos.Items(CboRemitos.SelectedIndex).Text.ToString()
            dr("CodigoRemito") = CboRemitos.SelectedValue.ToString()
            dr("Fecha") = Remito.BuscarFiltrado(CboRemitos.SelectedValue.ToString(), "", "", "", "", "", CboClientes.SelectedValue.ToString, "", "").Tables(0).Rows(0)("Fecha").ToString()
            dr("Valor") = Remito.BuscarFiltrado(CboRemitos.SelectedValue.ToString(), "", "", "", "", "", CboClientes.SelectedValue.ToString, "", "").Tables(0).Rows(0)("ValorCotizado").ToString()
            dr("iva") = (Math.Round(CDbl(dr("Valor").ToString()) * IVA)).ToString()
            dr("SubTotal") = Math.Round(CDbl(dr("Valor").ToString()) - CDbl(dr("Valor").ToString()) * IVA).ToString()
            'dr("SubTotal") = (Math.Round(CDbl(dr("Valor").ToString()) * IVA)).ToString()
            '            dr("SubTotal") = (Math.Round(CDbl(dr("Valor").ToString()) / IVA)).ToString()
            'dr("Iva") = (Math.Round(CDbl(dr("Valor").ToString()) - CDbl(dr("Valor").ToString()) * IVA)).ToString()
            DtsRemito.Tables(0).Rows.Add(dr)
            LblTotal.Text = (CDbl(LblTotal.Text) + CDbl(dr("Valor").ToString())).ToString()
            LblSubtotal.Text = (CDbl(LblSubtotal.Text) + CDbl(dr("SubTotal").ToString())).ToString()
            LblIva.Text = (CDbl(LblIva.Text) + CDbl(dr("IVA").ToString())).ToString()
            GridRemito.DataSource = DtsRemito
            GridRemito.DataBind()
            CboRemitos.Enabled = False
            CboRemitos.Items(CboRemitos.SelectedIndex).Enabled = False

            Dim i As Integer
            For i = 0 To CboRemitos.Items.Count() - 1
                CboRemitos.Enabled = CboRemitos.Enabled Or CboRemitos.Items(i).Enabled
            Next
        End If

    End Sub
    Sub VerificarTalonario()
        Dim dtsTipoTalonario As DataSet
        dtsTipoTalonario = Talonario.BuscarFiltrado("", TxtNumero.Text, TxtNumero.Text, "", "", "3", TipoTalonario.Buscar("", LblNumero.Text.Substring(0, 1), "FACTURA").Tables(0).Rows(0)("IdTipoTalonario").ToString())
        If dtsTipoTalonario.Tables(0).Rows.Count() = 0 Then
            LblErrorTalonario.Text = "Error, Talonario no Habilitado."
            HfIdTalonario.Value = ""
            LnkGuardar.Visible = False
        Else
            LnkGuardar.Visible = True
            HfIdTalonario.Value = dtsTipoTalonario.Tables(0).Rows(0)("IdTalonario").ToString()
            LblErrorTalonario.Text = ""
        End If
        If TxtNumero.Text <> "00000001" Then
            TxtNumero.Enabled = False
        Else
            TxtNumero.Enabled = True
        End If
        RVNumeracion.MinimumValue = TxtNumero.Text
    End Sub
    Protected Sub CboClientes_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CboClientes.SelectedIndexChanged
        If Cliente.Listar(CboClientes.SelectedValue.ToString(), "", "", "", "", "", "", "", "", "", "", "").Tables(0).Rows(0)("CodigoCategoria").ToString() = "1" Then
            LblNumero.Text = "A-0001-"
            TxtNumero.Text = Replace(Factura.ObtenerNumero("1").ToString().PadLeft(8), " ", "0")
        Else
            LblNumero.Text = "B-0001-"
            TxtNumero.Text = Replace(Factura.ObtenerNumero("2").ToString().PadLeft(8), " ", "0")
        End If
        VerificarTalonario()
        LLenarCboRemitos()
    End Sub
    Sub BorrarDataset(ByVal dts As DataSet)
        If dts.Tables(0).Rows.Count() > 0 Then
            dts.Tables(0).Rows.Remove(dts.Tables(0).Rows(0))
            BorrarDataset(dts)
        End If
    End Sub
    Protected Sub LinkCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkCancelar.Click
        Dim Cont As Integer
        Cont = 0
        For Cont = 0 To CboConceptos.Items.Count - 1
            CboConceptos.Items(Cont).Enabled = True
        Next
        For Cont = 0 To CboRemitos.Items.Count - 1
            CboRemitos.Items(Cont).Enabled = True
        Next

        CboConceptos.SelectedIndex = 0
        LimpiarCampos()
        TxtTotal.Enabled = True
        CboClientes.Enabled = True
        CboRemitos.Enabled = True
        CboClientes.SelectedIndex = 0
        DtsConcepto = Session("DtsVentas")
        DtsRemito = Session("DtsVentasRemito")
        LblTotal.Text = "0,00"
        LblSubtotal.Text = "0,00"
        LblIva.Text = "0,00"
        BorrarDataset(DtsConcepto)
        BorrarDataset(DtsRemito)
        CboClientes_SelectedIndexChanged(sender, e)
        GridConcepto.DataSource = DtsConcepto
        GridConcepto.DataBind()
        GridRemito.DataSource = DtsRemito
        GridRemito.DataBind()

    End Sub

    Protected Sub LinkNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkNuevo.Click
        LinkCancelar_Click(sender, e)
    End Sub

    Protected Sub LnkGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkGuardar.Click
        If CboClientes.SelectedValue <> -1 Then

            If CDbl(LblTotal.Text) > 0 Then
                Dim i As Integer
                Dim ErrorInsert As Boolean = False
                Dim IdFactura As String = Factura.Insertar((LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", ""), LblSubtotal.Text, LblTotal.Text, LblIva.Text, CboClientes.SelectedValue.ToString(), Cliente.Listar(CboClientes.SelectedValue.ToString(), "", "", "", "", "", "", "", "", "", "", "").Tables(0).Rows(0)("CodigoCategoria").ToString(), HfIdTalonario.Value.ToString())
                ErrorInsert = IdFactura = ""
                If Not ErrorInsert Then
                    DtsConcepto = Session("DtsVentas")
                    For i = 0 To DtsConcepto.Tables(0).Rows.Count - 1
                        ErrorInsert = ErrorInsert Or Not DetalleFacturaVenta.Insertar(DtsConcepto.Tables(0).Rows(i)("Subtotal").ToString(), DtsConcepto.Tables(0).Rows(i)("Total").ToString(), DtsConcepto.Tables(0).Rows(i)("IVA").ToString(), IdFactura, DtsConcepto.Tables(0).Rows(i)("CodigoConcepto").ToString(), "")
                    Next
                    DtsRemito = Session("DtsVentasRemito")
                    For i = 0 To DtsRemito.Tables(0).Rows.Count - 1
                        ErrorInsert = ErrorInsert Or Not DetalleFacturaVenta.Insertar(DtsRemito.Tables(0).Rows(i)("Subtotal").ToString(), DtsRemito.Tables(0).Rows(i)("Valor").ToString(), DtsRemito.Tables(0).Rows(i)("IVA").ToString(), IdFactura, "", DtsRemito.Tables(0).Rows(i)("CodigoRemito").ToString())
                    Next
                    If Not ErrorInsert Then
                        For i = 0 To DtsRemito.Tables(0).Rows.Count - 1
                            ErrorInsert = ErrorInsert Or Not Remito.Modificar(CInt(DtsRemito.Tables(0).Rows(i)("CodigoRemito").ToString()), 0, New DateTime, 0, 0, "", IdFactura)
                        Next
                    End If

                    If ErrorInsert Then
                        DetalleFacturaVenta.Eliminar("", IdFactura)
                        Factura.Eliminar(IdFactura)
                        For i = 0 To DtsRemito.Tables(0).Rows.Count - 1
                            Remito.Modificar(CInt(DtsRemito.Tables(0).Rows(i)("CodigoRemito").ToString()), 0, New DateTime, 0, 0, "", -1)
                        Next

                        LblError.Text = "Error, La factura no se ha grabado."
                    Else
                        Session("DtsImpresionDeFactura") = Factura.PrepararImpresion(IdFactura)
                        LinkCancelar_Click(sender, e)
                        Response.Write("<SCRIPT LANGUAGE='JavaScript'> var popup = window.open('../Reportes/RptImpresionComprobante.aspx',(new Date().getTime()),'Width=800,Height=600,Scrollbars=YES,Resizable=YES,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO') </SCRIPT>")
                    End If
                Else
                    LblError.Text = "Error, La factura no se ha grabado."
                End If
            Else
                LblError.Text = "Error, La factura no posee detalle."
            End If
        Else
            LblError.Text = "Error, Falta cargar el cliente."
        End If

    End Sub
    Protected Sub GridRemito_RowCommand(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridRemito.RowCommand
        If e.CommandName = "Remover" Then
            CboRemitos.Items(CboRemitos.Items.IndexOf(CboRemitos.Items.FindByValue(CInt(e.CommandSource.Parent.Parent.FindControl("HFIdRemito").value.ToString())))).Enabled = True
            LblTotal.Text = (CDbl(LblTotal.Text) - CDbl(e.CommandSource.Parent.Parent.FindControl("LblValorCotizado").text.ToString())).ToString()
            LblSubtotal.Text = (CDbl(LblSubtotal.Text) - CDbl(e.CommandSource.Parent.Parent.FindControl("LblSubtotalRemito").text.ToString())).ToString()
            LblIva.Text = (CDbl(LblIva.Text) - CDbl(e.CommandSource.Parent.Parent.FindControl("LblIvaRemito").text.ToString())).ToString()
            DtsRemito = Session("DtsVentasRemito")
            DtsRemito.Tables(0).Rows.Remove(DtsRemito.Tables(0).Rows(CInt(e.CommandSource.parent.parent.RowIndex)))
            GridRemito.DataSource = DtsRemito
            GridRemito.DataBind()
            CboRemitos.Enabled = Not CboRemitos.Text = ""
            CboClientes.Enabled = DtsRemito.Tables(0).Rows.Count = 0
        End If
    End Sub

    Protected Sub LnkMasInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkMasInfo.Click
        Me.Response.Write("<script languaje='javascript'>var popup = window.open('FrmListarDetalleRemitoServicio.aspx?IDRemito=" + CboRemitos.SelectedValue.ToString() + "',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')</script>")
    End Sub

    Protected Sub GridRemito_RowDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridRemito.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim IntLnkMasInformacion As LinkButton = e.Row.FindControl("LnkMasInformacion")
            Dim IntHFIdRemito As HiddenField = e.Row.FindControl("HFIdRemito")
            IntLnkMasInformacion.OnClientClick = "javascript:var popup = window.open('FrmListarDetalleRemitoServicio.aspx?IDRemito=" + IntHFIdRemito.Value.ToString() + "',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
        End If
    End Sub

End Class